package org.s3.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.s3.project.common.JwtUtils;
import org.s3.project.common.R;
import org.s3.project.entity.Admin;
import org.s3.project.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.HashMap;
import java.util.List;

/**
 * @author cfx
 * @version 1.0
 * @Description
 * @date 2025/2/9 9:26
 */
@CrossOrigin(origins = "*")
@RestController
public class AdminController {
    @Autowired
    private AdminService adminService;
    @PostMapping("loginAdmin")
    public R getAdmin(@RequestBody Admin user){

        Admin u = adminService.login(user);
        if(u!=null) {
            //生成token
            HashMap<String, Object> map = new HashMap<>();
            map.put("adminId",u.getId());
            String jwtToken = JwtUtils.createJwtToken(map);
            System.out.println("jwtToken = " + jwtToken);
            return new R().add("token",jwtToken);
        }

        return new R().setMsg("出错了").setCode(500);
    }

    @GetMapping("getUsernameByToken")
    public R getUsernameByToken(@RequestHeader("Authorization") String token) {
        try {
            // 使用现有的 getJwtToken 方法获取 adminId
            Integer adminId = JwtUtils.getJwtToken(token, "adminId");
            // 根据 adminId 查询用户名
            Admin admin = adminService.getAdminById(adminId);
            if (admin != null) {
                return new R().add("username", admin.getUsername());
            } else {
                return new R().setMsg("未找到用户信息").setCode(404);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new R().setMsg("token 解析失败").setCode(500);
        }
    }

    // 新增获取管理员资料的接口
    @GetMapping("getAdminProfile")
    public R getAdminProfile(@RequestHeader("Authorization") String token) {
        try {
            // 解析 token 获取 adminId
            Integer adminId = JwtUtils.getJwtToken(token, "adminId");
            // 根据 adminId 查询管理员资料
            Admin admin = adminService.getAdminById(adminId);
            if (admin != null) {
                return new R().add("adminProfile", admin);
            } else {
                return new R().setMsg("未找到用户信息").setCode(404);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new R().setMsg("token 解析失败").setCode(500);
        }
    }


}
